package com.qf.lanzhou.blog.api.controller.login;

import com.qf.lanzhou.blog.api.controller.BaseServletPost;
import com.qf.lanzhou.blog.api.pojo.entity.Role;
import com.qf.lanzhou.blog.api.pojo.entity.User;
import com.qf.lanzhou.blog.api.service.GetRoleService;
import com.qf.lanzhou.blog.api.service.LoginService;
import com.qf.lanzhou.blog.api.service.impl.login.GetRoleServiceImpl;
import com.qf.lanzhou.blog.api.service.impl.login.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author LEON-HE
 */
@WebServlet("/login.do")
public class LoginServlet extends BaseServletPost {
    private LoginService loginService = new LoginServiceImpl();
    private GetRoleService getRoleService = new GetRoleServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("开始登录");
        User loginUser = paramsToEntity(req,User.class);
        try{
            System.out.println("开始登录验证");
            User dbUser = loginService.checkLogin(loginUser);
            List<Role> roles = getRoleService.getRoleList(dbUser.getId());
            req.getSession().setAttribute("role",roles);
            req.getSession().setAttribute("user",dbUser);
            successResultWrite(dbUser,resp);
            System.out.println("登录成功");
        }catch (RuntimeException e){
            String errorMsg = e.getMessage();
            failedResultWrite(errorMsg,resp);
            System.out.println("登录失败");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
